<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use App\Models\ClassCourseModel;
use Illuminate\Http\Request;
use App\Models\Course;
use App\Models\CourseModel;
use App\Models\ImgModel;
use App\Models\CoursePackageModel;

class CourseController extends Controller
{
    public function list(Request $request) {
        $courses = CourseModel::where('company_id', $request->company_id)->get();
        return self::sendOk($courses);
    }
    
    public function page(Request $request) {
        $courses = CourseModel::where('company_id', $request->company_id)
        ->with('packages')
        ->with('type')
        ->paginate($request->per_page ?? 10, ['*'], 'page', $request->page ?? 1);
        return self::sendOk($courses);
    }

    public function save(Request $request) {
        $id = $request->input('id', 0);
        if($id) {
            $course = CourseModel::find($request->id);
            if (!$course) {
                return self::sendError('课程不存在');
            }
            if ($course->company_id != $request->company_id) {
                return self::sendError('课程不属于该公司');
            }
            $oldImg = $course->img;
        } else {
            $course = new CourseModel();
            $oldImg = null;
        }

        
        $data = $request->only(
            'type_id',
            'company_id',
            'name', 
            'img',
            'status',
            'desc',
            'time_len',
            'commission_type',
            'commission_fixed',
            'commission_num_base_price',
            'commission_num_base_num',
            'commission_num_per',
            'commission_stage');
        $course->fill($data);
        $course->save();
        if ($oldImg && ($oldImg != $course->img)) {
            ImgModel::useImg($course->img);
        }

        if ($id) {
            // 同步班级课程名称
            ClassCourseModel::where('course_id', $course->id)->update(['course_name' => $course->name]); 

            // 同步佣金提成信息
        }
        
        // 将薪酬规则同步到每一门课程
        if($request->commission_same == 1) {
            CourseModel::where('company_id', $course->company_id)->update([
                'commission_type' => $course->commission_type,
                'commission_fixed' => $course->commission_fixed,
                'commission_num_base_price' => $course->commission_num_base_price,
                'commission_num_base_num' => $course->commission_num_base_num,
                'commission_num_per' => $course->commission_num_per,
                'commission_stage' => $course->commission_stage,
            ]);
        }

        // 处理套餐
        $this->add_package($course->id, $request->packages?? []);
        return self::sendOk($course);
    }

    public function delete(Request $request) {
        $course = CourseModel::find($request->id);
        if ($course->company_id!= $request->company_id) {
            return self::sendError('课程不属于该公司');
        }
        $course->delete();

        // 删除图片
        // 删除套餐

        return self::sendOk();
    }

    public function info(Request $request) {
        $course = CourseModel::with('packages')->find($request->id);
        if (!$course) {
            return self::sendError('课程不存在');
        }
        if ($course->company_id!= $request->company_id) {
            return self::sendError('课程不属于该公司');
        }
        return self::sendOk($course);
    }

    private function add_package($courseId, $packages) {
        $oldPackages = CoursePackageModel::where('course_id', $courseId)->get();
        $keepIds = [];
        foreach ($packages as $package) {
            if (isset($package['id']) && $package['id']) {
                $keepIds[] = $package['id'];
            }
            
            // 更新
            if ($package['id']) {
                $oldPackage = CoursePackageModel::find($package['id']);
                if ($oldPackage) {
                    $oldPackage->fill($package);
                    $oldPackage->save();
                }
            } else { // 新增
                $package['course_id'] = $courseId;
                $newPackage = new CoursePackageModel();
                $newPackage->fill($package);
                $newPackage->save();
            }
        }
        // 把已经不存在的套餐删除掉
        foreach ($oldPackages as $oldPackage) {
            if (!in_array($oldPackage->id, $keepIds)) {
                $oldPackage->delete();
            }
        }
    }
}
